<template>
  <div class="dialog">
    <el-dialog :title="'疫病处理'" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="处理时间" class="w50p" prop="dealDate">
          <el-date-picker v-model="formData.dealDate" type="datetime" placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss" clearable @change="queryIotData" />
        </el-form-item>
        <el-form-item label="水温" class="w50p" prop="waterTemperature">
          <el-input v-model="formData.waterTemperature" type="number" clearable placeholder="未获取到传感器水温数据，请输入">
            <template slot="append">°C</template>
          </el-input>
        </el-form-item>
        <el-form-item label="处理人" class="w50p" prop="staffName">
          <el-select filterable clearable disabled v-model="formData.staffName" placeholder="请选择">
            <el-option v-for="(item, index) in staffList" :label="item.staffName" :value="item.staffName"
              :key="index + 'staff'" />
          </el-select>
        </el-form-item>
        <el-row :gutter="15">
          <el-table ref="rightTableData" :data="formData.diseaseDealDetailList" tooltip-effect="dark"
            highlight-current-row border stripe class="rightTableData">
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column label="用药名称" prop="name" align="center" min-width="120">
              <template slot-scope="scope">
                <div style="margin-top: 21px;">
                  <el-form-item :prop="'diseaseDealDetailList.' + scope.$index + '.materialId'" class="w100p"
                    :rules="{ required: true, message: '用药名称不能为空', trigger: 'blur' }">
                    <el-select filterable clearable v-model="scope.row.materialId"
                      @change="materialChange($event, scope.$index)">
                      <el-option v-for="item of materialList" :key="item.materialId + 'materialId'" :label="item.name"
                        :value="item.materialId" />
                    </el-select>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="用药量" prop="amount" min-width="95">
              <template slot-scope="scope">
                <el-form-item :prop="'diseaseDealDetailList.' + scope.$index + '.amount'"
                  :rules="{ required: true, message: '用药量不能为空', trigger: 'blur' }">
                  <el-input :disabled="!scope.row.materialId" v-model="scope.row.amount" type="number"
                    style="margin-top: 21px;" @change="() => {
                      if (scope.row.amount < 0) { scope.row.amount = ''; return }
                      scope.row.num = scope.row.amount / materialObj[scope.row.materialId].ratioNum
                      $set(formData.diseaseDealDetailList, scope.$index, {
                        materialId: scope.row.materialId,
                        num: scope.row.num,
                        amount: scope.row.amount
                      })
                    }">
                    <i slot="suffix" class="el-input__icon">{{
                      scope.row.materialId ? materialObj[scope.row.materialId].unit : '' }}</i>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="amount" min-width="95">
              <template slot-scope="scope">
                <el-form-item :prop="'diseaseDealDetailList.' + scope.$index + '.num'"
                  :rules="{ required: true, message: '数量不能为空', trigger: 'blur' }">
                  <el-input :disabled="!scope.row.materialId" v-model="scope.row.num" @change="() => {
                    if (scope.row.num < 0) { scope.row.num = ''; return }
                    scope.row.amount = scope.row.num * materialObj[scope.row.materialId].ratioNum
                    $set(formData.diseaseDealDetailList, scope.$index, {
                      materialId: scope.row.materialId,
                      num: scope.row.num,
                      amount: scope.row.amount
                    })
                  }" type="number" style="margin-top: 21px;">
                    <i slot="suffix" class="el-input__icon">{{
                      scope.row.materialId ? materialObj[scope.row.materialId].aUnit : '' }}</i>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="药品用法" prop="usage" min-width="95">
              <template slot-scope="scope">
                <el-input v-model="scope.row.usage" />
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="80">
              <template slot-scope="scope">
                <el-button type="text" style="color:red;text-decoration: underline;" size="small" @click.native.prevent="
                  deleteRow(scope.$index)
                  " :disabled="formData.diseaseDealDetailList.length <= 1">删除</el-button>
              </template>
            </el-table-column>
            <template slot="empty">
              <div>请添加数据</div>
            </template>
          </el-table>
        </el-row>
        <el-row :gutter="15">
          <el-button type="info" plain icon="el-icon-circle-plus-outline" class="addInfo"
            @click="addButInfo">添加</el-button>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HealthTaskHandlingApi from "@/api/health-management/health-task-handling";
import BatchMangeApi from "@/api/batch-mange";
import EnvironmentalDataApi from "@/api/iot-monitoring/environmental-data-monitoring";
import StaffApi from "@/api/basic-info-manage/staff";
import MaterialApi from "@/api/basic-info-manage/material";
import { dialogMixin } from "@/utils/dialogMixin";
import store from "@/store";
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    show: {
      type: Boolean,
      default: false
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {
      formData: {},
      materialList: [],
      staffList: [],
      batchList: [],
      fishPondId: undefined,
      rules: {
        staffName: [
          { required: true, message: "请输入员工名称", trigger: ["blur"] }
        ],
      },
      showDialog: this.show
    };
  },

  computed: {
    materialObj() {
      return store.state.basicData.material;
    }
  },
  watch: {
    show(v) {
      this.showDialog = v;
    },
    nowChanceStau(v) {
      if (v === 'add') {
        let staffId = sessionStorage.getItem("staffId")
        let staffName = sessionStorage.getItem("staffName")
        this.formData.staffId = staffId == 1 ? this.staffList[0].staffId : staffId
        this.formData.staffName = staffId == 1 ? this.staffList[0].staffName : staffName
        this.formData.dealDate = this.getNowTime()
        this.formData.diseaseDealDetailList = [{}]
        this.formData.waterTemperature = ""
        this.formData = { ...this.formData }
        console.log(this.formData)
      }
      if (v === 'edit') {
        console.log(this.editObject)
        this.formData = this.editObject
      }
    },
    editObject(v) {
      if (v.diseaseRecordId) {
        this.formData.diseaseRecordId = v.diseaseRecordId;
        this.fishPondId = v.fishPondId;
        this.queryIotData()
      }
    },
  },
  created() {
  },
  mounted() {
    this.queryMaterial()
    this.queryStaff()
    this.queryBatch({ pondId: this.formData.pondId })
  },
  methods: {
    materialChange(e, index) {
      this.materialList.forEach(item => {
        if (!item.basicUnitName) {
          item.basicUnitName = ''
        }
        if (!item.auxiliaryUnitName) {
          item.auxiliaryUnitName = ''
        }
        // let auxiliaryUnitNo = `${item.basicUnitName} ${item.basicUnitName && item.auxiliaryUnitName ? '/' : ''}${item.auxiliaryUnitName}`
        let auxiliaryUnitNo = `${item.basicUnitName}`
        if (item.materialId === e) {
          this.$set(this.formData.diseaseDealDetailList[index], 'auxiliaryUnitNo', auxiliaryUnitNo)
        }
      })
    },
    queryIotData(e) {
      const params = {
        // collectTime:this.getNowTime(),
        fishPondId: this.fishPondId,
        dataTypeName: "水温",
      }
      if (e) params.collectTime = e;
      else params.collectTime = this.getNowTime();
      EnvironmentalDataApi.queryDataByTime(params).then(res => {
        if (res.data) {
          this.$set(this.formData, 'waterTemperature', res.data)
        } else {
          this.$set(this.formData, 'waterTemperature', '')
        };
      })
    },
    pondChange(e) {
      BatchMangeApi.queryBatchByPondId({ pondId: e }).then(res => {
        this.batchList = res.data
      })
    },
    queryBatch() {
      BatchMangeApi.queryByCondition().then(res => {
        this.batchList = res.data
      })
    },
    queryStaff() {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data
      })
    },
    queryMaterial() {
      MaterialApi.queryByCondition({ materialTypeNo: 'drug' }).then(res => {
        this.materialList = res.data;
      })
    },
    // 点击添加按按钮
    addButInfo() {
      let list = {
        materialId: null,
      };
      this.formData.diseaseDealDetailList.push(list);
    },
    // 删除改行
    deleteRow(index) {
      this.formData.diseaseDealDetailList.splice(index, 1);
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            HealthTaskHandlingApi.edit(this.formData).then(res => {
              if (res.success) {
                this.$message.success("处理成功");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            HealthTaskHandlingApi.add(this.formData).then(res => {
              if (res.success) {
                this.$message.success("处理成功");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.formData = {}
      this.$emit("cancelDialog");
      this.$refs.ruleForm.resetFields()
    }
  }
};
</script>

<style lang="scss" scoped>
.addInfo {
  width: 100%;
}

::v-deep .el-table {
  position: relative;
}
</style>
